﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MeTalker.Aide.Service;
using MeTalker.Securitys.Cryptography;
using MeTalker.Aide.data;
using System.Diagnostics;
using System.Web;

namespace MeTalker.Aide.Forms
{
    internal delegate void LoginProcHandler(object sender, byte[] b);

    internal partial class frmLoad : MeForm
    {
        LoginProcHandler login;
        int count = 1;
        AESHelper aes = new AESHelper();
        string userId;
        string password;
        string sessionId;
        string info;
        public frmLoad()
        {
            InitializeComponent();
            //MuchInfo.Logs.MILog.Info("D="+FileFactory.BaseDirectory);
            //MessageBox.Show(FileFactory.BaseDirectory);
            //Console.WriteLine(GetHDID());
            login = new LoginProcHandler(Login);
            lblState.Text = "";

            //Console.WriteLine("sid=222".Substring(4, 7 - 4));
            try
            {
                byte[] b = FileFactory.ReaderFile(FileFactory.BaseDirectory + "user.dat");
                string msg = Encoding.UTF8.GetString(aes.Decrypt(b));
                if (!string.IsNullOrEmpty(msg))
                {
                    string[] msgs = msg.Split(',');
                    txtUserId.Text = msgs[0].Split('=')[1];
                    txtPassword.Text = msgs[1].Split('=')[1];
                    sessionId = msgs[2].Split('=')[1];
                    chkPass.Checked = bool.Parse(msgs[3].Split('=')[1]);
                }

                //info = "H=" + GetHd() + ",N=" + GetNetworkInterfaceToString() + ",C=" + GetCPUSerialNo();
                //info = ByteToHexX2(aes.Encrypt(Encoding.UTF8.GetBytes(info)));
                //pictureBox.Image = new Bitmap("icons/load.jpg");
                
            }
            catch { }
        }

        private void frmLoad_Load(object sender, EventArgs e)
        {
            try
            {
                //Console.WriteLine("frmLoad_Load:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //byte[] b = FileFactory.ReaderFile(FileFactory.BaseDirectory + "user.dat");
                //string msg = Encoding.UTF8.GetString(aes.Decrypt(b));
                //if (!string.IsNullOrEmpty(msg))
                //{
                //    string[] msgs = msg.Split(',');
                //    txtUserId.Text = msgs[0].Split('=')[1];
                //    txtPassword.Text = msgs[1].Split('=')[1];
                //    sessionId = msgs[2].Split('=')[1];
                //    chkPass.Checked = bool.Parse(msgs[3].Split('=')[1]);
                if (!string.IsNullOrEmpty(txtUserId.Text) && !string.IsNullOrEmpty(txtPassword.Text) && DataFactory.SystemConfig.AutoRun)
                {
                    btnLogin.Enabled = false;
                    login.BeginInvoke(this, null, null, null);
                }
                //}
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("frmLoad_Load", ex);
            }
        }

        private void frmLoad_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        void Login(object sender, byte[] b1)
        {
            HttpClient client = new HttpClient();
            try
            {

                byte[] b = client.Request(string.Format(UtilHelper.LOGIN_URL, UtilHelper.TYPE_USER_LOGIN, new Random().Next()), aes.Encrypt(ToBytes()));
                DispProc(client, b);
            }
            catch
            {
            }
        }

        void DispProc(object sender, byte[] b)
        {
            LoginProcHandler del = delegate(object obj, byte[] b1)
            {
                try
                {
                    if (b == null)
                    {
                        // lblState.Text = "登录失败！无法连接服务！";
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_conntect_error_str);
                        MeMessageBox.ShowInformation("连接服务器失败,请重试!");
                        return;
                    }
                    
                    string msg = Encoding.UTF8.GetString(b);
                    
                    if (msg.Equals(UtilHelper.LOGIN_FAIL))
                    {
                        if (count >= 3)
                        {
                            MeMessageBox.ShowInformation("您已经连续三次输入密码错误,程序将自动关闭!");
                            //MeMessageBox.ShowInformation(DataFactory.Tips.tip_login_fail_exit_str);
                            CloseCheck(DialogResult.No);
                            return;
                        }
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_password_error_str);
                        MeMessageBox.ShowInformation("密码错误,请重新输入!");
                        count++;
                    }
                    else if (msg.Equals(UtilHelper.LOGIN_OVER_VALID))
                    {
                       DialogResult result = MeMessageBox.ShowInformation("此用户使用许可已经到期,请联系官方客服QQ(563174509)购买或续费!");
                       if (result == DialogResult.OK)
                       {
                           System.Diagnostics.Process.Start("tencent://message/?uin=563174509&Site=www.jinlansoft.com&Menu=yes");
                       }
                     //   MeMessageBox.ShowInformation("此用户使用许可已经到期，请您购买或续费!");
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_over_vaild_str);
                        //CloseCheck(DialogResult.No);
                        //lblState.Text = "用户已超过有效期！";
                    }
                    else if (msg.Equals(UtilHelper.LOGIN_USER_EXIST))
                    {
                        //lblState.Text = "该用户正在使用该系统！";
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_exist_str);
                        MeMessageBox.ShowInformation("该用户正在使用该系统!");
                    }
                    else if (msg.Equals(UtilHelper.USER_INVALID))
                    {
                        //lblState.Text = "该用户被禁用！";
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_vaild_str);
                        MeMessageBox.ShowInformation("此用户已被禁止登录!");
                        //CloseCheck(DialogResult.No);
                    }
                    else if (msg.Equals(UtilHelper.USER_INACTIVE_ACTIVATE))
                    {
                        //lblState.Text = "该用户未激活！";
                        MeMessageBox.ShowInformation("该用户未激活!");
                    }
                    else if (msg.Equals(UtilHelper.LOGIN_DOUBLE))
                    {
                        //lblState.Text = "帐户别处登录！";
                       // MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_other_str);
                        MeMessageBox.ShowInformation("此用户已经登录,不能重复登录!");
                    }
                    else if (msg.Equals(UtilHelper.USER_NOT_EXIST))
                    {
                        //lblState.Text = "帐户别处登录！";
                        //MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_not_exist_str);
                        MeMessageBox.ShowInformation("此用户不存在,请先注册!");
                    }
                    else
                    {
                        bool flag = DataFactory.InitUser(Encoding.UTF8.GetString(aes.Decrypt(b)));
                        if (DataFactory.User != null && flag && DataFactory.User.IsSuccess)
                        {
                            DataFactory.User.UserName = userId;
                            DataFactory.User.Passwd = password;
                            sessionId = DataFactory.User.SessionId;
                            DataFactory.User.IsSave = chkPass.Checked;
                            UtilHelper.Update(userId, password, sessionId, chkPass.Checked);
                            //if (chkPass.Checked)
                            //{
                            //    FileFactory.WriterFile(FileFactory.BaseDirectory+ "user.dat", aes.Encrypt(Encoding.UTF8.GetBytes(string.Format("u={0},p={1},s={2},v=true", userId, password, sessionId))));
                            //}
                            //else
                            //{
                            //    FileFactory.WriterFile(FileFactory.BaseDirectory + "user.dat", aes.Encrypt(Encoding.UTF8.GetBytes(string.Format("u=,p=,s={0},v=false", sessionId))));
                            //}
                            //lblState.Text = "用户验证成功, 正在加载数据... ";
                            //MeMessageBox.ShowInformation("用户验证成功, 正在加载数据... ");
                            FileFactory.WriterFile(FileFactory.BaseDirectory + "user.license", aes.Encrypt(b));
                            CloseCheck(DialogResult.Yes);
                        }
                        else
                        {
                            // lblState.Text = "系统错误！";
                            MeMessageBox.ShowInformation("系统错误！");
                        }
                    }
                }
                catch
                {
                    //lblState.Text = "系统错误！";
                }
                finally
                {
                    btnLogin.Enabled = true;
                }
            };
            this.BeginInvoke(del, new object[] { sender, b });
        }

        void CloseCheck(DialogResult result)
        {

            DialogResult = result;
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserId.Text))
            {
                //MeMessageBox.ShowInformation(DataFactory.Tips.tip_user_not_null_str);
                MeMessageBox.ShowInformation("用户名不能为空!");
                
                //   lblState.Text = "用户名不能为空!";
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                MeMessageBox.ShowInformation("密码不能为空!");
                //MeMessageBox.ShowInformation(DataFactory.Tips.tip_password_not_null_str);
                //lblState.Text = "密码不能为空!";
                return;
            }
            //MeMessageBox.ShowInformation("正在验证用户...");
            //lblState.Text = "正在验证用户...";
            btnLogin.Enabled = false;
            login.BeginInvoke(this, null, null, null);
        }

        byte[] ToBytes()
        {
            userId = txtUserId.Text;
            password = txtPassword.Text;
            StringBuilder sb = new StringBuilder();
            sb.Append(UtilHelper.CONST_FLAG);
            sb.Append("<root>");
            sb.Append(string.Format("<UD>{0}</UD>", userId));
            sb.Append(string.Format("<PD>{0}</PD>", password));
            sb.Append(string.Format("<SID>{0}</SID>", sessionId));
            sb.Append(string.Format("<HD>{0}</HD>", Convert.ToBase64String(Encoding.UTF8.GetBytes(GetHDID()))));
            sb.Append(string.Format("<NI>{0}</NI>", GetNetworkInterfaceToString()));
            sb.Append(string.Format("<CP>{0}</CP>", GetCPUSerialNo()));
            sb.Append("</root>");
            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private void lblReg_Click(object sender, EventArgs e)
        {
            if (btnLogin.Enabled)
                new frmReg().ShowDialog();
        }

        private void txtUserId_KeyDown(object sender, KeyEventArgs e)
        {
            txtPassword.Text = "";
        }
    }
}